package com.kuangchi.test.hash;

import com.kuangchi.test.hash.SortedMapWithVirtualNode;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @version v1.0
 * @类描述：
 * @项目名称：
 * @包名： com.kuangchi.test.service
 * @类名称：HashCodeService
 * @创建人：YIHANG.XU
 * @创建时间：2021/12/311:04 上午
 * @修改人：YIHANG.XU
 * @修改时间：2021/12/311:04 上午
 * @修改备注：
 * @Copyright
 */
@Component
public class HashCodeService implements InitializingBean {
    private static SortedMapWithVirtualNode sortedMapWithVirtualNode = new SortedMapWithVirtualNode();

    // Hash 环
    private static SortedMap<Integer, String> treeMapHash;
    // 表数量
    private static final int SERVERS_NUM = 5;
    // 虚拟表
    private static final int VIRTUAL_NODES = 10;

    //
    private static ArrayList<String> serverList = new ArrayList<>();

    private void init() {
        // 构造服务器数据
        for (int i = 0; i < SERVERS_NUM; i++) {
            String s = i + "";
            serverList.add(s);
        }
        // 构建 Hash 环
        treeMapHash = sortedMapWithVirtualNode.buildHash(new TreeMap<Integer, String>());
        // 将服务器的虚拟节点添加到 Hash 环中
        for (String s : serverList) {
            for (int i = 0; i < VIRTUAL_NODES; i++) {
                String VNNode = s + "&&VN" + String.valueOf(i);
                sortedMapWithVirtualNode.addServerNode(VNNode);
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        init();
    }

    public String getTableCode(String userId) {
        String code = sortedMapWithVirtualNode.selectServerNode(userId);
        return code;
    }
}
